package com.wb.mas.ui.webview;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;

import com.google.gson.Gson;
import com.wb.mas.BR;
import com.wb.mas.R;
import com.wb.mas.app.AppViewModelFactory;
import com.wb.mas.databinding.ActWebviewBinding;
import com.wb.mas.entity.JsOrderData;

import me.goldze.mvvmhabit.base.BaseActivity;

/**
 * Copyright (C) 2018,
 * WebViewActivity
 * <p>
 * Description
 *
 * @author yue
 * @version 1.0
 * <p>
 * Ver 1.0, 2019-05-08, yue, Create file
 */
public class WebViewActivity extends BaseActivity<ActWebviewBinding, WebViewViewModel> {

    private String title;

    private String url;

    public JsOrderData orderData;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.act_webview;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initParam() {
        super.initParam();
        Intent intent = getIntent();
        title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        orderData= (JsOrderData) intent.getSerializableExtra("orderData");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel.titleText.set(title);
        initWeb(binding.webContent);
        binding.webContent.loadUrl(url);
    }

    @SuppressLint("JavascriptInterface")
    private void initWeb(WebView webView) {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可


        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        if (orderData!=null){
            webView.addJavascriptInterface(new JavaScript(), "jsi");
        }
    }

    @Override
    public WebViewViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        WebViewViewModel webViewViewModel = ViewModelProviders.of(this, factory).get(WebViewViewModel.class);
        return webViewViewModel;
    }


    private final class JavaScript {

        @JavascriptInterface
        @SuppressLint("JavascriptInterface")
        public void getOrderInfoData() {

            WebViewActivity.this.runOnUiThread(new Runnable() {

                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void run() {
                    if (binding.webContent != null && orderData != null) {
                        // Android版本变量
                        final int version = Build.VERSION.SDK_INT;

                        StringBuilder builder = new StringBuilder();
                        builder.append("javascript:call_back_getOrderInfoData(");
                        builder.append(new Gson().toJson(orderData));
                        builder.append(")");

                        if (version < 18) {
                            binding.webContent.loadUrl(builder.toString());
                        } else {
                            binding.webContent.evaluateJavascript(builder.toString(), new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String value) {

                                }
                            });
                        }
                    }
                }
            });
        }
    }

}
